package predicates

import (
	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	"sigs.k8s.io/controller-runtime/pkg/event"
	"sigs.k8s.io/controller-runtime/pkg/predicate"
)

// CommandUpdateCompleted is a predicate that returns true if the command changes from other phase to completed phase
func CommandUpdateCompleted() predicate.Funcs {
	return predicate.Funcs{
		UpdateFunc: func(e event.UpdateEvent) bool {
			if oldCommand := e.ObjectOld.(*agentv1beta1.Command); oldCommand != nil {
				newCommand := e.ObjectNew.(*agentv1beta1.Command)
				if newCommand == nil {
					return false
				}
				// For command, Reconciler expects that all nodes specified by command have been executed and have a result
				switch {
				case newCommand == nil:
					return false
				case len(newCommand.Status) < len(oldCommand.Status):
					return false
				case newCommand.Spec.NodeName != "" && len(newCommand.Status) != 1:
					return false
				case newCommand.Spec.NodeSelector == nil && len(newCommand.Status) == newCommand.Spec.NodeSelector.Size():
					return false
				}
				return true
			}
			return false
		},
		CreateFunc:  func(event.CreateEvent) bool { return false },
		DeleteFunc:  func(event.DeleteEvent) bool { return false },
		GenericFunc: func(event.GenericEvent) bool { return false },
	}
}
